/* eslint-disable prettier/prettier */
import React from "react";
import ReactDom from "react-dom";
import { Button, Icon, Modal, Spin, Tabs } from "antd";
import { connect } from "react-redux";
import MockScan from "components/scan-mock";
import ScanSnap from "components/scan-snap";
import KeDaScan from "components/keDaScan";
import CanonScan from "components/canon-scan/canon-scan";
import { eventTrack, messages } from "share/common";
import scannerImg from "images/components/scanner.gif";
import scannerBtnStepImg from "images/components/scanner-btn-step.gif";
import "styles/components/scanner-button.scss";
import ScannerButtonService from "components/scanner-button/scanner-button.service";
import configureStore from "stores";
const { TabPane } = Tabs
import mainService from "containers/main.service";
// 扫描按钮组
// 兼容不同的扫描仪处理
class ScannerButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: true,
      isFirstScan: false,
      scanModalVisible: false,
      scanCounter: {
        success: 0,
        error: 0,
        num: 0, //计数器，不论一个文件识别出几张发票，识别一次即记为1
      },
      totalScanNum: 0,
      loadedImg1: false,
      loadedImg2: false,
      showNotice: false,
      scanIntroduction: {},
      OCR2: {},
    };
    this.interval = null;
    this.currentTime = null;
    this.currentNoticeKey = null;
    this.noticeDom = null;
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    this.initScanIntroduction();
    this.initNotificationDom();
    // 浏览器安全问题 需要用户操作才能只能佳能检测
    console.info(`enableScan is ${this.props.enableScan}`)
    if (this.props.enableScan === "INIT") {
      mainService.checkScan(configureStore.store.dispatch);
    }
  }
  // 扫发票说明提示文案运营平台维护 若有则提示 若没有则不显示信息
  initScanIntroduction = () => {
    ScannerButtonService.getCommonProblemByCode(["ScanInvoice", "OCR2"]).then((res) => {
      if (res.data[0] && res.data[0].id) {
        this.setState({
          scanIntroduction: res.data[0],
          OCR2: res.data[1],
        });
      }
    });
  };
  onStartScan = () => {
    this.setState({ isFirstScan: true });
  };
  handleScan = (params) => {
    console.info("看看有没有走到handleScan 这一步")
    const { isFirstScan } = this.state;
    if (isFirstScan) {
      this.currentTime = Date.now();
    }
    return new Promise(() => {
      let newTotalScanNum = this.state.totalScanNum + 1;
      if (isFirstScan && !this.state.showNotice) {
        this.setState({ scanModalVisible: true });
      }
      this.setState({ isFirstScan: false, totalScanNum: newTotalScanNum });
      this.props.onScan(params, this.state.scanCounter);
      this.onWatchStopScan();
      this.showNotification();
      this.onEventTrack({
        responseTime: Math.floor(Date.now() - this.currentTime) / 1000,
      });
      this.currentTime = Date.now();
    });
  };
  onEventTrack = ({ errorInfo = false, notOCRFlag = false, disabled = false, responseTime = 0 }) => {
    const { tenantInfo, enableScan } = this.props;
    let errorType = "无";
    if (notOCRFlag) {
      errorType = "未开通OCR";
    }
    if (disabled) {
      errorType = "未检测到驱动";
    }
    if (errorInfo) {
      errorType = errorInfo;
    }
    eventTrack({
      category: "财务扫发票",
      action: "租户名称+卷票机类型+报错类型+调用识别接口时间",
      label: [tenantInfo.tenantName, enableScan, errorType, responseTime + "s"].join(" "),
    });
  };
  /**
   * 超过一秒钟没有新的扫描结果就认为扫描结束
   */
  onWatchStopScan = () => {
    const self = this;
    if (this.interval) {
      clearInterval(this.interval);
    }
    this.interval = setInterval(() => {
      if (self.state.totalScanNum && self.state.scanCounter.num === self.state.totalScanNum) {
        clearInterval(this.interval);
        this.stopScan();
      }
    }, 1000);
  };

  stopScan = () => {
    console.info("看看有没有走到stopScan这一步")
    setTimeout(() => {
      if (this.currentNoticeKey) {
        this.setState({ showNotice: false });
        this.closeNotificationDom();
      }
      this.currentNoticeKey = null;
      this.setState(
        {
          scanModalVisible: false,
        },
        () => {
          console.info('扫描已结束')
          this.props.onStopScan();
          this.interval = null;
          this.currentTime = null;
          setTimeout(() => {
            if (!this.state.isFirstScan) {
              this.setState({
                scanCounter: {
                  success: 0,
                  error: 0,
                  num: 0,
                },
                totalScanNum: 0,
              });
            }
          }, 200);
        }
      );
    }, 1000);
  };

  refreshScanProps = (nextState) => {
    this.setState({ ...nextState }, () => {
      this.showNotification();
    });
  };

  handleClickInfo = () => {
    const { scanIntroduction, OCR2 } = this.state;
    Modal.info({
      className: "modal-scanner-button-style",
      title: scanIntroduction.question,
      content: (
        <Tabs defaultActiveKey="1">
          <TabPane tab={messages('common-1.key1356')/*功能简介*/} key="1">
            <section
              dangerouslySetInnerHTML={{ __html: scanIntroduction.answer }}
              className="modal-scan-invoice"
            />
          </TabPane>
          <TabPane tab={messages('common-1.key1357')/*使用技巧*/} key="2">
            <section dangerouslySetInnerHTML={{ __html: OCR2.answer }} className="modal-scan-invoice"/>
          </TabPane>
        </Tabs>
      ),
    });
  };
  // 手动关闭弹窗
  handleHideScanModal = () => {
    this.setState(
      {
        scanModalVisible: false,
      },
      () => {
        this.currentNoticeKey = `open${Date.now()}`;
        this.showNotification();
      }
    );
  };
  handleHideScanNotice = () => {
    this.setState({ showNotice: false });
    this.closeNotificationDom();
    this.currentNoticeKey = null;
  };
  showNotification = () => {
    console.info("this.currentNoticeKey", this.currentNoticeKey)
    if (!this.currentNoticeKey) {
      return !1;
    }
    this.noticeDom.className = "scanner-notification show";
    this.initNotificationDom();
    this.setState({ showNotice: true });
  };
  // 样式问题 这个dom需要挂载到body下
  initNotificationDom = () => {
    const { scanCounter, totalScanNum } = this.state;
    let isInit = false;
    if (!this.noticeDom) {
      isInit = true;
      this.noticeDom = document.createElement("div");
      this.noticeDom.className = "scanner-notification";
    }
    let JSXDom = (
      <div className="scanner-notification-wrap">
        <Spin className="icon-scanner-notification" />
        <div>
          <p className="second-title" style={{ margin: 0 }}>
            {
              messages("common-1.key119", {
                arg1: totalScanNum,
              }) /*发票正在扫描中，已扫描{arg1}张图片*/
            }
          </p>
          <p className="third-title" style={{ margin: 0 }}>
            {
              messages("common-1.key120", {
                arg1: scanCounter.success,
              }) /*识别成功{arg1}张*/
            }
            {scanCounter.error
              ? `，${
                  messages("common-1.key121", {
                    arg1: scanCounter.error,
                  }) /*识别失败{arg1}张…*/
                }`
              : ""}
          </p>
        </div>
        <Icon type="close" className="notification-icon-close" onClick={this.handleHideScanNotice} />
      </div>
    );
    ReactDom.render(JSXDom, this.noticeDom);
    isInit && document.body.append(this.noticeDom);
  };
  closeNotificationDom = () => {
    this.noticeDom.className = "scanner-notification";
  };
  renderIntroductionIcon = () => {
    let { scanIntroduction } = this.state;
    if (scanIntroduction.answer) {
      return <Icon type="info-circle-o" onClick={this.handleClickInfo} className="scan-info" />;
    } else {
      return "";
    }
  };
  renderScanArea = () => {
    let { enableScan, buttonProps, text, showOCRFlag } = this.props;
    if (enableScan === 'MOCK') {
      return (
        <span className="scan-snap-button">
          <MockScan
            buttonProps={buttonProps}
            showOCRFlag={showOCRFlag}
            onScan={this.handleScan}
            onStartScan={this.onStartScan}
            onEventTrack={this.onEventTrack}
          >
            {text}
          </MockScan>
          {this.renderIntroductionIcon()}
        </span>
      );
    } else if (enableScan === "KEDA") {
      return (
        <span className="scan-snap-button">
          <KeDaScan
            text={text}
            showOCRFlag={showOCRFlag}
            buttonProps={buttonProps}
            onScan={this.handleScan}
            onStartScan={this.onStartScan}
            onEventTrack={this.onEventTrack}
          />
          {this.renderIntroductionIcon()}
        </span>
      );
    } else if (enableScan === "SCAN_SNAP") {
      return (
        <span className="scan-snap-button">
          <ScanSnap
            buttonProps={buttonProps}
            showOCRFlag={showOCRFlag}
            onScan={this.handleScan}
            onStartScan={this.onStartScan}
            onEventTrack={this.onEventTrack}
          >
            {text}
          </ScanSnap>
          {this.renderIntroductionIcon()}
        </span>
      );
    } else {
      return (
        <span className="scan-snap-button">
          <CanonScan
            buttonProps={buttonProps}
            text={text}
            showOCRFlag={showOCRFlag}
            onScan={this.handleScan}
            onStartScan={this.onStartScan}
            onEventTrack={this.onEventTrack}
          ></CanonScan>
          {this.renderIntroductionIcon()}
        </span>
      );
    }
  };

  render() {
    const { scanCounter, scanModalVisible, totalScanNum, loadedImg1, loadedImg2 } = this.state;
    return (
      <span>
        {this.renderScanArea()}
        <Modal
          width={660}
          footer={
            <Button type="primary" onClick={this.handleHideScanModal}>
              {messages("common-1.key41") /*关闭*/}
            </Button>
          }
          visible={scanModalVisible}
          closable={false}
          wrapClassName="scanner-button"
        >
          <Spin spinning={!loadedImg1 || !loadedImg2}>
            <p className="scanner-button-title">
              <img src={scannerImg} className="scanner-button-img" onLoad={() => this.setState({ loadedImg1: true })} />
            </p>
            <div className="scanner-button-subtitle">
              <img
                src={scannerBtnStepImg}
                className="scanner-button-step-img"
                onLoad={() => this.setState({ loadedImg2: true })}
              />
              <div>
                <p>
                  {
                    messages("common-1.key119", {
                      arg1: totalScanNum,
                    }) /*发票正在扫描中，已扫描{arg1}张图片*/
                  }
                </p>
                <p>
                  {
                    messages("common-1.key120", {
                      arg1: scanCounter.success,
                    }) /*识别成功{arg1}张*/
                  }
                  {scanCounter.error
                    ? `，${
                        messages("common-1.key121", {
                          arg1: scanCounter.error,
                        }) /*识别失败{arg1}张…*/
                      }`
                    : ""}
                </p>
              </div>
            </div>
            <div className="desc-wrap">
              <p className="third-title">{messages("common-1.key1248") /*识别完毕后此弹窗会自动关闭；*/}</p>
              <p className="third-title">{messages("common-1.key1249") /*关闭后，系统仍然会继续处理扫描和识别*/}</p>
            </div>
          </Spin>
        </Modal>
      </span>
    );
  }
}
ScannerButton.propTypes = {
  onScan: React.PropTypes.func,
  text: React.PropTypes.string,
  buttonProps: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    enableScan: state.main.enableScan,
    tenantInfo: state.login.tenant,
    language: state.main.language,
  };
}

export default connect(mapStateToProps)(ScannerButton);
